package com.itliang.manager.factory;

import com.itliang.constant.Constants;
import com.itliang.constant.MqttConstants;
import com.itliang.core.model.entity.SysLoginInfo;
import com.itliang.core.model.entity.SysOperLog;
import com.itliang.mqtt.service.SubscribeDataService;
import com.itliang.service.log.SysLoginInfoService;
import com.itliang.service.log.SysOperLogService;
import com.itliang.service.log.impl.SysLoginInfoServiceImpl;
import com.itliang.utils.ServletUtils;
import com.itliang.utils.ip.AddressUtils;
import com.itliang.utils.ip.IpUtils;
import com.itliang.utils.spring.SpringUtils;
import eu.bitwalker.useragentutils.UserAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.TimerTask;

import static com.itliang.constant.MqttConstants.COLLECTION_DATA_TOPIC;

/**
 * 异步工厂（产生任务用）
 *
 * @author : liangzhuoyuan
 */
public class AsyncFactory {


    private static final Logger log = LoggerFactory.getLogger("AsyncFactory");

    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息
     * @param args     列表
     * @return 任务task
     */
    public static TimerTask recordLoginInfo(final String username, final Integer status, final String message,
                                            final Object... args) {
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = IpUtils.getIpAddr();
        return new TimerTask() {
            @Override
            public void run() {
                String address = AddressUtils.getRealAddressByIP(ip);
                // 获取客户端操作系统
                String os = userAgent.getOperatingSystem().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();
                // 封装对象
                SysLoginInfo loginInfo = SysLoginInfo.builder()
                        .userName(username)
                        .ipaddr(ip)
                        .loginLocation(address)
                        .browser(browser)
                        .os(os)
                        .msg(message)
                        .loginTime(new Date()).build();
                // 日志状态
                if (status == 0) {
                    loginInfo.setStatus(Constants.SUCCESS);
                } else if (status == 1) {
                    loginInfo.setStatus(Constants.FAIL);
                }
                // 插入数据
                SysLoginInfoServiceImpl bean = (SysLoginInfoServiceImpl) SpringUtils.getBean(SysLoginInfoService.class);
                bean.save(loginInfo);
            }
        };
    }

    /**
     * 处理从EMQX订阅到的消息
     *
     * @param topic 消息主题
     * @param message 消息内容
     * @return
     */
    public static TimerTask handlerSubscribeMessage(String topic, String message) {
        return new TimerTask() {
            @Override
            public void run() {
                // 从spring容器拿到服务bean
                SubscribeDataService subscribeDataService = SpringUtils.getBean(SubscribeDataService.class);
                // 根据不同主题，选择不同的处理方法
                if (COLLECTION_DATA_TOPIC.equals(topic)) {
                    subscribeDataService.handlerCollectionData(message);
                }
                if (MqttConstants.ESP_TO_SPRINGBOOT_TOPIC.equals(topic)) {
                    subscribeDataService.sendStatusToESP8266(message);
                }
            }
        };
    }

    /**
     * 操作日志记录
     *
     * @return 任务task
     */
    public static TimerTask recordOper(SysOperLog operLog) {
        return new TimerTask() {
            @Override
            public void run() {
                // 从spring容器拿到服务bean
                SysOperLogService service = SpringUtils.getBean(SysOperLogService.class);
                service.save(operLog);
            }
        };
    }

}
